package com.forever7776.qiniu.core.rpc;

import com.alibaba.fastjson.JSONObject;
import com.forever7776.qiniu.core.QiNiuApi;
import com.forever7776.qiniu.core.constants.SystemConstant;
import com.forever7776.qiniu.core.entity.SysFile;
import com.forever7776.qiniu.core.service.ISysFileService;
import com.forever7776.qiniu.core.utils.DateUtil;
import com.forever7776.qiniu.core.utils.FileUtil;
import com.forever7776.qiniu.core.utils.ResultUtil;
import com.forever7776.qiniu.remote.common.enums.QiNiuEnum;
import com.forever7776.qiniu.remote.common.enums.ResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * <p>
 * 七牛保存类
 * </p>
 *
 * @author 0
 * @date 2018-03-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class QiNiuService {

    private static Logger logger = LoggerFactory.getLogger(QiNiuService.class);

    @Autowired(required = false)
    private ISysFileService iSysFileService;

    /**
     * 图片超过2MB加上廋身参数
     */
    private static final long NEED_IMAGE_SLIM = 1024 * 1024 * 2;

    private static final String IMAGE_SLIM_NAME = "?imageslim";

    public JSONObject pic(MultipartFile multipartFile, String userId) throws IOException {
        long begin = System.currentTimeMillis();
        JSONObject result = new JSONObject();
        if (multipartFile.isEmpty()) {
            result.put("msg", "图片为空");
            result.put("success", false);
            return result;
        }
        String originFileName = multipartFile.getOriginalFilename();
        if (!StringUtils.contains(SystemConstant.QINIU_SUFFIXIMAGE, FileUtil.getFileSuffix(originFileName).toUpperCase())) {
            result.put("msg", "图片类型不对");
            result.put("success", false);
            return result;
        }
        long fileSize = multipartFile.getSize();
        String newFileName = userId + SystemConstant.QINIU_SLASH + originFileName;
        SysFile sysFile = new SysFile();
        sysFile.setUserId(userId);
        sysFile.setFileType(0);
        sysFile.setFileName(originFileName);
        sysFile.setFileSize(fileSize);
        if (fileSize > NEED_IMAGE_SLIM) {
            sysFile.setFileKey(originFileName + IMAGE_SLIM_NAME);
        }
        result = uploadFileByte(multipartFile.getBytes(), newFileName, sysFile);
        logger.info("本次上传耗时：{}ms,文件名：{}，上传完毕时间：{}", (System.currentTimeMillis() - begin), originFileName, DateUtil.format(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
        return result;
    }

    public JSONObject uploadFileByte(byte[] fileByte, String fileKey, SysFile sysFile) {
        JSONObject result = ResultUtil.getSuccessResult("上传成功");
        try {
            result = QiNiuApi.uploadFileByte(fileByte, fileKey);
            save(result, sysFile);
            return result;
        } catch (Exception e) {
            result.put("code", ResultEnum.STATUS.FAIL.getCode());
            logger.error("uploadProcess@QiNiuUpload save model error", e);
        }

        return result;
    }

    public void save(JSONObject jo, SysFile sysFile) {
        if ("success".equals(jo.getString("result_code"))) {
            String key = jo.getString("key");
            sysFile.setFileStatus(QiNiuEnum.STATUS.SUCCESS.getKey());
            sysFile.setFileSuffix(FileUtil.getFileSuffix(key));
            sysFile.setInsertDate(new Date());
            logger.info("[upload]上传结果返回-->key:" + key);
        } else {
            logger.info("[upload]上传失败");
            sysFile.setFileStatus(QiNiuEnum.STATUS.FAIL.getKey());
        }
        if (iSysFileService != null) {
            iSysFileService.insert(sysFile);
        }

    }
}
